package com.ruoyi.rsikManage.controller;


import com.ruoyi.common.constant.HttpStatus;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.framework.web.service.TokenService;
import com.ruoyi.rsikManage.domain.AlgoScenario;
import com.ruoyi.rsikManage.domain.AlgoScenarioRes;
import com.ruoyi.rsikManage.domain.Algorithm;
import com.ruoyi.rsikManage.domain.CategoryAlarmCount;
import com.ruoyi.rsikManage.domain.algoTree.AlgoCountVo;
import com.ruoyi.rsikManage.domain.vo.AlgoAndMonitors;
import com.ruoyi.rsikManage.domain.algoTree.AlgoTreeVo;
import com.ruoyi.rsikManage.domain.vo.MonitorAndAlgos;
import com.ruoyi.rsikManage.service.AlgorithmService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import java.util.*;

@RequestMapping("")
@RestController
@Slf4j
@SuppressWarnings("all")
public class AlgorithmController extends BaseController {
    String contentType = "application/json";
    private HttpHeaders headers = new HttpHeaders();
    @Autowired
    private ServletContext servletContext;
    @Autowired
    private RestTemplate restTemplate;

    @Autowired
    AlgorithmService algorithmService;

    @Autowired
    private TokenService tokenService;

    @Value("${jy.ip}")
    private String JY_IP;
    /**
     * 查询算法列表中每个区域分类的报警个数
     */
    @GetMapping("rsikManage/algoScenario/categoryAlarm")
    public AjaxResult countCategoryAlarm(Date startTime, Date endTime) {
        List<CategoryAlarmCount> res = algorithmService.countCategoryAlarm(startTime, endTime);
        return AjaxResult.success(res);
    }
    /**
     * 查询各算法场景的报警情况
     */
    @GetMapping("rsikManage/algoScenario/list")
    public AjaxResult getAlgoScenarioList(String category, Date startTime, Date endTime) {
        AlgoScenarioRes res = algorithmService.selectAlgoScenarioList(category, startTime, endTime);
        int algoDeployCount = 0;
        int algoStatusCount = 0;
        int alarmCount = 0;
        if (res == null) {
            return AjaxResult.success(new AlgoScenarioRes());
        }
        List<AlgoScenario> algoScenarioList = res.getAlgoScenarioList();
        for (AlgoScenario algoScenario : algoScenarioList) {

            String monitorNames = algoScenario.getMonitorNames();
            String alarmName = algoScenario.getAlarmName();
            String ApeIds = algoScenario.getMonitorIds();


            algoScenario.setApeNames(monitorNames != null && !monitorNames.isEmpty() ? monitorNames.split(",") : null);
            algoScenario.setApeIds(ApeIds != null && !ApeIds.isEmpty() ? ApeIds.split(",") : null);
            algoScenario.setAlarmTypeNames(alarmName != null && !alarmName.isEmpty() ? alarmName.split(",") : null);

            if (algoScenario.getAlgoDeploy().equals("已部署")) {
                algoDeployCount++;
            }
            if (algoScenario.getAlgoStatus().equals("启用")) {
                algoStatusCount++;
            }
            alarmCount += algoScenario.getAlarmCount();
        }
        res.setAlgoScenarioCount(algoScenarioList.size());
        res.setAlgoDeployCount(algoDeployCount);
        res.setAlgoStatusCount(algoStatusCount);
        res.setAlarmCount(alarmCount);
        return success(res);
    }

    /**
     * 设置请求头参数
     */
    public void setHeaders(HttpHeaders headers) {
        headers.set("Authorization", servletContext.getAttribute("access_token").toString());
        headers.set("Content-Type", contentType);
    }

    //  算法文件查询
    @GetMapping("/alarmEvent/algorithm")
    public Map<String, Object> algorithmandFile() {
        setHeaders(headers);
        String url = "http://"+JY_IP+":11125/api/vias/v2/awh/deployment/installed-algos";
        HttpEntity httpEntity = new HttpEntity<>(headers);
        ResponseEntity<Map> response = restTemplate.exchange(url, HttpMethod.GET, httpEntity, Map.class);

        Map map = response.getBody();
        //System.out.println(body);
        // return response.getBody();
        return map;
    }

    /**
     * 算法-监控点 列表
     */
    @GetMapping("rsikManage/algorithmAndMonitors")
    public TableDataInfo algorithmAndMonitors(Algorithm algorithm, Integer pageNum, Integer pageSize) {
        List<AlgoAndMonitors> resList = algorithmService.algorithmAndMonitors(algorithm);

        int total = resList.size();
        int start = (pageNum - 1) * pageSize;
        int end = Math.min(start + pageSize, total);
        if (pageNum != null && pageSize != null) {
            resList = resList.subList(start, end);
        }

        TableDataInfo rspData = new TableDataInfo();
        rspData.setCode(HttpStatus.SUCCESS);
        rspData.setMsg("查询成功");
        rspData.setRows(resList);
        rspData.setTotal(total);
        return rspData;
    }

    /**
     * 监控点-算法 列表
     */
    @GetMapping("rsikManage/monitorAndAlgorithms/v1")
    public TableDataInfo monitorAndAlgorithmV1(String monitorName,Integer pageNum, Integer pageSize) {
        List<MonitorAndAlgos> resList = algorithmService.monitorAndAlgorithmV1(monitorName);

        int total = resList.size();
        int start = (pageNum - 1) * pageSize;
        int end = Math.min(start + pageSize, total);
        if (pageNum != null && pageSize != null) {
            resList = resList.subList(start, end);
        }

        TableDataInfo rspData = new TableDataInfo();
        rspData.setCode(HttpStatus.SUCCESS);
        rspData.setMsg("查询成功");
        rspData.setRows(resList);
        rspData.setTotal(total);
        return rspData;
    }

    /**
     * 监控点-算法 列表
     */
    @PostMapping("rsikManage/monitorAndAlgorithms")
    public TableDataInfo monitorAndAlgorithm(HttpServletRequest httpServletRequest,
                                             String monitorName,
                                             List<Long> unitCodes,
                                             Integer pageNum,
                                             Integer pageSize) {


        // 如果 unitCodes 为空或为空列表，则从登录用户信息中获取
        if (unitCodes == null || unitCodes.isEmpty()) {
            unitCodes = tokenService.getLoginUserUnitCodes(httpServletRequest);
        }
        List<MonitorAndAlgos> resList = algorithmService.monitorAndAlgorithm(unitCodes,monitorName);

        int total = resList.size();
        int start = (pageNum - 1) * pageSize;
        int end = Math.min(start + pageSize, total);
        if (pageNum != null && pageSize != null) {
            resList = resList.subList(start, end);
        }

        TableDataInfo rspData = new TableDataInfo();
        rspData.setCode(HttpStatus.SUCCESS);
        rspData.setMsg("查询成功");
        rspData.setRows(resList);
        rspData.setTotal(total);
        return rspData;
    }
    /**
     *
     * 算法树(弃用)
     */
    @GetMapping("rsikManage/category-place-algos")
    public AjaxResult placeAndAlgorithms() {
        return AjaxResult.success(algorithmService.placeCategoryAndPlaceAndAlgorithms2());
    }

    /**
     * 算法树（新）
     */
    @GetMapping("rsikManage/algoTree/v2")
    public AjaxResult getAlgoTree(@RequestParam Integer categoryId) {
        AlgoTreeVo res = algorithmService.selectAlgoTree(categoryId);
        return AjaxResult.success(res);
    }

    /**
     * 算法树（新）
     * 新增煤矿编码 unitCode 进行筛选
     *
     */
    @GetMapping("rsikManage/algoTree")
    public AjaxResult getAlgoTree(@RequestParam Integer categoryId,Long unitCode) {


        AlgoTreeVo res = algorithmService.selectAlgoTreeV2(categoryId,unitCode);
        return AjaxResult.success(res);
    }




    /**
     * 统计算法树中的算法个数 （单矿版本）
     */
    @GetMapping("rsikManage/algoTree/total-number-of-tree-algos/v2")
    public AjaxResult totalNumberOfAlgosInAlgoTree(HttpServletRequest httpServletRequest) {

        List<AlgoCountVo> res  = algorithmService.totalNumberOfAlgosInAlgoTree();
        return AjaxResult.success(res);
    }

    /**
     * 统计算法树中的算法个数 （单矿版本）
     * 修改时间 24/10/28
     * 修改内容 新增权限管理
     */
    @GetMapping("rsikManage/algoTree/total-number-of-tree-algos")
    public AjaxResult totalNumberOfAlgosInAlgoTreeForUnitCodes(Long unitCode) {
        List<AlgoCountVo> res  = algorithmService.totalNumberOfAlgosInAlgoTreeForUnitCodes(unitCode);
        return AjaxResult.success(res);
    }

    /**
     * 统计算法树中的算法个数 （集团版本）
     */
    @GetMapping("rsikManage/algoTree/total-number-of-tree-algos/group")
    public AjaxResult totalNumberOfAlgosInAlgoTreeGroup(HttpServletRequest httpServletRequest) {

        // 获取当前登录用户的单位代码
        List<Long> unitcodes = tokenService.getLoginUserUnitCodes(httpServletRequest);

        List<AlgoCountVo> res  = algorithmService.totalNumberOfAlgosInAlgoTreeGroup();
        return AjaxResult.success(res);
    }

    /**
     *
     */
    @GetMapping("rsikManage/installed-algos-list")
    public TableDataInfo algoList(Algorithm algorithm, Integer pageNum, Integer pageSize) {
        List<Algorithm> resList = algorithmService.algoList(algorithm);

        int total = resList.size();
        int start = (pageNum - 1) * pageSize;
        int end = Math.min(start + pageSize, total);
        if (pageNum != null && pageSize != null) {
            resList = resList.subList(start, end);
        }

        TableDataInfo rspData = new TableDataInfo();
        rspData.setCode(HttpStatus.SUCCESS);
        rspData.setMsg("查询成功");
        rspData.setRows(resList);
        rspData.setTotal(total);
        return rspData;
    }

    /**
     * 查询某监控点的算法
     */
    @GetMapping("rsikManage/algorithmsInTheMonitor")
    public TableDataInfo algorithmsInTheMonitor(String monitorId, Integer pageNum, Integer pageSize) {
        List<Algorithm> resList = algorithmService.algorithmsInTheMonitor(monitorId);

        int total = resList.size();
        int start = (pageNum - 1) * pageSize;
        int end = Math.min(start + pageSize, total);
        if (pageNum != null && pageSize != null) {
            resList = resList.subList(start, end);
        }

        TableDataInfo rspData = new TableDataInfo();
        rspData.setCode(HttpStatus.SUCCESS);
        rspData.setMsg("查询成功");
        rspData.setRows(resList);
        rspData.setTotal(total);

        return rspData;
    }

}
